package com.example.myapplication.camera.util;

import android.content.Context;
import android.media.Image;
import android.os.Build;
import android.util.Log;

import androidx.annotation.RequiresApi;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;


/**
 * Create By TreeRoot
 * Create Time: 2024/08/12 01:25
 * Class Name: ImageSaver
 * Description:
 * 保存图片的工具类
 *
 * @author TreeRoot
 */
public class ImageSaver implements Runnable {
    private final Image mImage;
    private static final String savePath = "/sdcard/proton/picture/";

    public ImageSaver(Image image, Context context) {
        this.mImage = image;
    }

    @Override
    public void run() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss", Locale.CHINA);
        String fName = sdf.format(new Date()) + "_output.png";
        writeImageToFolder(mImage, fName);
    }

    /**
     * 将Image对象写入文件夹
     *
     * @param image    Image对象
     * @param fileName 文件名
     */
    public static void writeImageToFolder(Image image, String fileName) {
        try {
            // 获取第一个平面的缓冲区
            ByteBuffer buffer = image.getPlanes()[0].getBuffer();
            byte[] bytes = new byte[buffer.remaining()];
            buffer.get(bytes);

            // 构建文件对象
            File folder = new File(savePath);
            if (!folder.exists()) {
                if (!folder.mkdirs()) {
                    Log.e("ImageWriter", "Failed to create folder");
                    return;
                }
            }
            File file = new File(folder, fileName);

            try (FileOutputStream fos = new FileOutputStream(file)) {
                fos.write(bytes);
            } catch (IOException e) {
                Log.e("ImageWriter", "Failed to write image", e);
            }
        } catch (Exception e) {
            Log.e("ImageWriter", "Error occurred", e);
        }
    }

}